<?php
/**
 * General utility functions
 * Split to require_once utils_shared.php for functions only
 * relevant to releasing module(s) to the Moodle community
 *
 * @copyright &copy; 2006 The Open University
 * @author D.A.Woolhead@open.ac.uk
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package local
 *//** */

require_once(dirname(__FILE__).'/utils_shared.php');

/**
 * Validate Course code-presentation string and return resultant part in array
 * 
 * @param string $course Course code - presentation
 * @param bool $ucase Convert everything to uppercase
 * @return array with 0=>code-pres, 1=>code, 2=>pres if valid, otherwise false
 */
function get_course_code_pres($course='', $ucase=true) {
    $matches = array();
    if ($ucase) {
        // Perform match on uppercased supplied course (obviously returning uppercased results)
        preg_match('/^([A-Z]+[0-9]{3})-([0-9]{2}[A-Z]?)$/', strtoupper($course), $matches);
    } else {
        // Perform match preserving case of supplied course
        preg_match('/^([a-zA-Z]+[0-9]{3})-([0-9]{2}[a-zA-Z]?)$/', $course, $matches);
    }
    return $matches;
}

/**
 * Just like the PHP explode function, except that if you pass in an empty
 * string, you get an empy array out (instead of an array with one
 * element - the empty string). So this is what you want to use for 
 * parsing space or comma-separated strings into arrays.
 * @param string $separator the string to split on.
 * @param string $string the string to be split.
 * @return array the array of fragments.
 */
function explode_list($separator, $string) {
    if ($string) {
        return explode($separator, $string);
    } else {
        return array();
    }
}

/**
 * Returns the serial number that was just used for a particular column's 
 * autoincrement field.
 * @param string $table Table name
 * @param string $column Column name
 * @return int Value
 */    
function db_get_serial_number($table,$column='id') {
    global $CFG;
    if($CFG->dbtype=='postgres7') {
        $rs=db_do('SELECT currval(\''.$table.'_'.$column.'_seq\') AS frog');
        return $rs->fields['frog'];
        // TODO (sam) Implement for MySQL too
    } else {
        throw new Exception("Database type $CFG->dbtype currently unsupported");
    }                
}

/**
 * Converts from usernames to IDs.
 * @param array $usernames Array of usernames
 * @return array Associative array of usernames mapping to integer user IDs 
 *   (not necessarily in the same order; will not include duplicate entries)
 * @throws Exception If any user is not found 
 */
function convert_usernames($usernames) {
    if(count($usernames)==0) { 
        return array(); 
    }
    $first=true;
    $dbusernames='';
    foreach($usernames as $username) {
        if($first) {
            $first=false;
        } else {
            $dbusernames.=',';
        }
        $dbusernames.=db_q($username);
    }
    $rs=db_do("SELECT username,id FROM prefix_user WHERE username IN ($dbusernames)");
    $found=array();
    while(!$rs->EOF) {
        $found[$rs->fields['username']]=$rs->fields['id'];
        $rs->MoveNext();
    }
    foreach($usernames as $username) {
        if(!array_key_exists($username,$found)) {
            throw new Exception("Failed to find requested username $username",EXN_LOCAL_UNKNOwNUSERNAME);
        }
    }
    return $found;
}

/**
 * Checks if URL is one of those that the Library have broken back button for. If it is,
 * returns a revised URL that won't break the back button.
 * @param string $url URL to fix
 * @return string The fixed URL
 */
function repair_url($url) {

    $routesprefix='http://routes.open.ac.uk/ixbin/hixclient.exe?';
    if(strpos($url,$routesprefix)===0) {
        global $CFG;
        $url=$CFG->wwwroot.'/local/routeslink.php?q='.urlencode(substr($url,strlen($routesprefix)));
    }
    $libezproxyprefix='http://libezproxy.open.ac.uk/login?url=';
    if(strpos($url,$libezproxyprefix)===0) {
        global $CFG;
        $url=$CFG->wwwroot.'/local/libezproxylink.php?url='.urlencode(substr($url,strlen($libezproxyprefix)));
    }
    return $url;
}

?>